package com.bidianying.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import redis.clients.jedis.ShardedJedisPool;

import com.bidianying.entity.Result;
import com.bidianying.service.CityIpService;
import com.bidianying.service.CommonService;
import com.bidianying.service.GewaraService;
import com.bidianying.service.MaizuoService;
import com.bidianying.service.TaobaoService;
import com.bidianying.service.WebService;
import com.bidianying.util.LoadProperties;
import com.bidianying.util.RedisUtils;






@Controller
public class WebController extends BaseController{
	
	
	@Autowired
	private WebService webService;
	
	@Autowired
	private CityIpService cityIpService;
	
	@Autowired
	private ShardedJedisPool shardedJedisPool;
	
	@Autowired
	private GewaraService gewaraService;
	
	@Autowired
	private MaizuoService maizuoService;
	
	@Autowired
	private CommonService commonService;
	
	@Autowired
	private TaobaoService taobaoService;
	
	@RequestMapping("/city")
	public String city(){
		return "city";
	}
	
	@RequestMapping("/index")
	public ModelAndView index(HttpServletRequest req,HttpServletResponse response){
		ModelAndView model = new ModelAndView();
		String filmChannel = this.getRequestParamstr(req, "filmChannel");
		String citycodeReq = this.getRequestParamstr(req, "citycode");
		String ip = this.getReqIp(req);
		String citycodeIp = cityIpService.getCityByIp(ip);
		String citycodeCookie = "";
		//设置一个默认的citycode
		String citycode = "110000";
		String cityName = cityIpService.getCityNameById(citycode);
		Cookie[] coo = req.getCookies();
		if(coo!=null){
			for(Cookie c:coo){
		    	if(c.getName().equals("citycode")){ 
		    		citycodeCookie = c.getValue();
		    	}
		    }
		}
	    //如果手动选择了城市
	    if(!citycodeReq.equals("")){
	    	cityName = this.getRequestParamstr(req, "cityName");
			Cookie cookie = new Cookie("citycode",citycodeReq);  
		    cookie.setMaxAge(60*60*24*7);//保留7天  
		    response.addCookie(cookie);
		    citycode = citycodeReq;
		}
	    //如果没有选择城市，cookie中有城市的值
	    if(citycodeReq.equals("")&&!citycodeCookie.equals("")){
	    	citycode = citycodeCookie;
	    	cityName = cityIpService.getCityNameById(citycode);
	    }
	    //如果没有选择城市、cookie中也没有，则根据ip取得城市
	    if(citycodeReq.equals("")&&citycodeCookie.equals("")&&!citycodeIp.equals("")){
	    	citycode = citycodeIp;
	    	cityName = cityIpService.getCityNameById(citycode);
	    }
	    
		//拉取数据源
		Map<String,Object> map = new HashMap<String,Object>();
		if(filmChannel == null || filmChannel.equals("")){//默认从格瓦拉拉取数据
			//先从redis里取出数据
			String filmInfo = RedisUtils.hget(shardedJedisPool, "cityFilmInfo:"+citycode, "data");
			String filmNum =  RedisUtils.hget(shardedJedisPool, "cityFilmInfo:"+citycode, "filmNum");
			if(filmInfo!=null && filmNum!=null){
				JSONArray resultJson = JSONArray.fromObject(filmInfo);
				map.put("filmNum", filmNum);
				map.put("data", resultJson);
			}else{
				String url = LoadProperties.getProperty("/config.properties", "gewaraFilm");
				Map<String,String> data = new HashMap<String,String>();
				map = webService.getFilmInfoByUrl(url, data,citycode);
			}
		}
		model.addObject("resultData", map);
		model.addObject("cityName",cityName);
		model.setViewName("index");
		req.getSession().setAttribute("citycode", citycode);
		return model;
	}
	
	@RequestMapping("/movie/{movieId}")
	public String movieInfo(@PathVariable String movieId,HttpServletRequest req,Model model){
		if(movieId==null || movieId.equals("")){
			return "error";
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String citycodeCookie = "";
		String date = this.getRequestParamstr(req, "palyDate");
		if(date.equals("")){
			date = sdf.format(new Date());
		}
		Cookie[] coo = req.getCookies();
		if(coo!=null){
			for(Cookie c:coo){
		    	if(c.getName().equals("citycode")){ 
		    		citycodeCookie = c.getValue();
		    	}
		    }
		}
		if(citycodeCookie.equals("")){
			if(req.getSession().getAttribute("citycode")!=null){
				citycodeCookie = (String)req.getSession().getAttribute("citycode");
			}
		}
		Map<String,List<Map<String,String>>> areaInfo = gewaraService.getCinemaByMovie(date, movieId, citycodeCookie);
		List<Map<String,String>> dateInfo = gewaraService.getShowDateList(movieId);
		if(dateInfo.size()>6){
			dateInfo = dateInfo.subList(0, 7);
		}
		model.addAttribute("areaInfo", areaInfo);
		model.addAttribute("dateInfo",dateInfo);
		model.addAttribute("palyDate",date);
		model.addAttribute("movieId",movieId);
		return "movie";
	}
	
	@RequestMapping("/movie/getCommonOpiItem")
	@ResponseBody
	public Result getCommonOpiItem(HttpServletRequest req,Model model){
		String fyrq = this.getRequestParamstr(req, "fyrq");
		String movieId = this.getRequestParamstr(req, "movieId");
		String cinemaId = this.getRequestParamstr(req, "cinemaId");
		if(movieId==null || movieId.equals("")){
			return new Result(-1,"","params error!");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(fyrq.equals("")){
			fyrq = sdf.format(new Date());
		}
		List<Map<String,String>> resultList = gewaraService.getCommonOpiItem(fyrq, movieId, cinemaId);
		if(resultList.size()>0){
			return new Result(0,resultList,"success");
		}
		return new Result(-1,"","暂无数据!");
	}
	
	@RequestMapping("/movie/getPriceHref")
	@ResponseBody
	public Result getPriceHref(HttpServletRequest req){
		String fyrq = this.getRequestParamstr(req, "fyrq");
		String movieId = this.getRequestParamstr(req, "movieId");
		String cinemaId = this.getRequestParamstr(req, "cinemaId");
		if(movieId==null || movieId.equals("")){
			return new Result(-1,"","params error!");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(fyrq.equals("")){
			fyrq = sdf.format(new Date());
		}
		//格瓦拉的价格和购买链接
		Map<String, Map<String, String>> resultMap = gewaraService.getPriceHref(fyrq, movieId, cinemaId);
		if(resultMap.size()>0){
			return new Result(0,resultMap,"success");
		}
		return new Result(-1,"","暂无数据!");
	}
	@RequestMapping("/movie/getPriceHrefForMaizuo")
	@ResponseBody
	public Result getPriceHrefForMaizuo(HttpServletRequest req){
		String fyrq = this.getRequestParamstr(req, "fyrq");
		String movieId = this.getRequestParamstr(req, "movieId");
		String cinemaId = this.getRequestParamstr(req, "cinemaId");
		if(movieId==null || movieId.equals("")){
			return new Result(-1,"","params error!");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(fyrq.equals("")){
			fyrq = sdf.format(new Date());
		}
//		Map<String,Object> cinemaMap = commonService.getCinemaMapByCinemaId(cinemaId);
//		Map<String,Object> movieMap = commonService.getMovieMapByMovieId(movieId);
		String cinemaStr = RedisUtils.hget(shardedJedisPool, "cinemaMap", cinemaId);
		String movieStr = RedisUtils.hget(shardedJedisPool, "movieMap", movieId);
		JSONObject cinemaJson = JSONObject.fromObject(cinemaStr);
		JSONObject movieJson = JSONObject.fromObject(movieStr);
		if(cinemaJson.get("maizuoId") == null || movieJson.get("maizuoMovieId") == null){
			return new Result(-1,"","暂无数据!");
		}
		String maizuoCinemaId =  String.valueOf(cinemaJson.get("maizuoId"));
		String maizuoMovieId = String.valueOf(movieJson.get("maizuoMovieId"));
		Map<String, Map<String, String>> resultMap = maizuoService.getPriceHref(fyrq, maizuoMovieId, maizuoCinemaId);
		if(resultMap.size()>0){
			return new Result(0,resultMap,"success");
		}
		return new Result(-1,"","暂无数据!");
	}
	@RequestMapping("/movie/getPriceHrefForTaobao")
	@ResponseBody
	public Result getPriceHrefForTaobao(HttpServletRequest req){
		String fyrq = this.getRequestParamstr(req, "fyrq");
		String movieId = this.getRequestParamstr(req, "movieId");
		String cinemaId = this.getRequestParamstr(req, "cinemaId");
		if(movieId==null || movieId.equals("")){
			return new Result(-1,"","params error!");
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(fyrq.equals("")){
			fyrq = sdf.format(new Date());
		}
		String cinemaStr = RedisUtils.hget(shardedJedisPool, "cinemaMap", cinemaId);
		String movieStr = RedisUtils.hget(shardedJedisPool, "movieMap", movieId);
		JSONObject cinemaJson = JSONObject.fromObject(cinemaStr);
		JSONObject movieJson = JSONObject.fromObject(movieStr);
		if(cinemaJson.get("taobaoId") == null || movieJson.get("taobaoMovieId") == null){
			return new Result(-1,"","暂无数据!");
		}
		String taobaoCinemaId =  cinemaJson.getString("taobaoId");
		String taobaoMovieId = movieJson.getString("taobaoMovieId");
		
		Map<String, Map<String, String>> resultMap = taobaoService.getPriceHref(fyrq, taobaoMovieId, taobaoCinemaId);
		if(resultMap.size()>0){
			return new Result(0,resultMap,"success");
		}
		return new Result(-1,"","暂无数据!");
	}
}
